let base_conpermit_info = require("./models/base_conpermit_info")(sequelize, DataTypes);

const utils = require("./utils");
const { Op } = require("sequelize");

async function getlist(req,where,order) {
  let r = await base_conpermit_info.findAndCountAll({
    offset: ((req.query.pageNum ?? 1) - 1) * (req.query.pageSize ?? 0),
    limit: (req.query.pageSize ?? 100) * 1,
    where,
    order
  });
  return r;
}

app.get("/system/conpermit/list", async (req, res) => {
  try {
    let where = utils.getwhere(req.query);
    utils.setlike(where,'prjName',req);
    utils.setlike(where,'prjpwemitsNum',req);
    if(req.query["istask"]){
      utils.removewhere(where,'istask');
      where[Op.and].push({idConsproject:{[Op.is]:null}});
    }
    // where[Op.and].push({deletemark:0});
    let r = await getlist(req,where,[['acceptTime','DESC']]);
    res.send(r);
  } catch (err) {
    console.log(err);
    res.send("err");
  }
});

app.get("/system/conpermit/:id", async (req, res) => {
  let r = await base_conpermit_info.findByPk(req.params.id);
  res.send(r);
});

app.put("/system/conpermit", async (req, res) => {
  // let r = await consproject.findByPk(req.params.id);
  let r = await base_conpermit_info.update(req.body, {
    where: {
      id: req.body.id,
    },
  });
  res.send(r);
});

app.put("/system/relconpermit", async (req, res) => {
  // let r = await consproject.findByPk(req.params.id);
  let wherefield = req.body.prjpwemitsNumBase?'prjpwemitsNumBase':'prjpwemitsNum';
  req.body.reltime = new Date();
  req.body.reluser = 'admin';
  let r = await base_conpermit_info.update(req.body, {
    where: {
      [wherefield]: req.body[wherefield],
    },
  });
  res.send(r);
});

app.post("/system/conpermit", async (req, res) => {
  // delete req.body.id;
  req.body.deletemark = 0;
  let r = await base_conpermit_info.create(req.body);
  // console.log(r);
  res.send(r);
});

app.get("/system/conpermit/delete/:id", async (req, res) => {
  let r = await base_conpermit_info.update({deletemark:1},{
    where: {
      id: req.params.id,
    },
  });
  res.send(r);
});

app.get("/system/combineInfo",async(req,res)=>{
  //更新
  let r = await base_conpermit_info.update({prjpwemitsNumBase:req.query.permitsno.split(',')[0]},{
    where: {
      prjpwemitsNum: {[Op.in]:req.query.permitsno.split(',') },
    },
  });
  res.send(r);
})